package com.example.demo.config.shiro;

import com.example.demo.entity.Person;
import com.example.demo.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义的 Realm 这里进行 用户认证和授权的操作
 * 我们这里假定 user_lev =1 就是用户的操作，user_lev=2 就是 管理员的操作
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    LoginService loginService;


    /**
     * 这里进行授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("=======授权=====");
        String name=(String)principalCollection.getPrimaryPrincipal();
        System.out.println("身份信息为 "+name);

        // 查询数据库，获取 角色信息
        Person person=loginService.selectPersonByName(name);
        int lev=person.getUser_lev();

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        // 等级为 1 ,就是 user
        if(lev==1){
            simpleAuthorizationInfo.addRole("user");
            // 等级为 2 ,就是 admin
        }else{
            simpleAuthorizationInfo.addRole("admin");
        }
        return simpleAuthorizationInfo;
    }



    /**
     * 认证是否有这个用户
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 获取用户的 name
        String name=(String) authenticationToken.getPrincipal();
        Person person=loginService.selectPersonByName(name);
        System.out.println("=======认证=====");
        System.out.println(name);
        // 表示有这个用户
        if(person!=null&&person.getUser_name()!=null){
            String password=person.getUser_password();
            String salt=person.getUser_salt();

            // 这里是 和 Controller 层中的UsernamePasswordToken 密码进行比较
            SimpleAuthenticationInfo simpleAuthorizationInfo=new SimpleAuthenticationInfo(name,password,new Md5Hash(salt),this.getName());
            return simpleAuthorizationInfo;
        }
        return null;
    }
}
